
#include "TextAsset.h"
#include "File.h"
#include "tools/StringManager.h"
#include <assert.h>

using namespace unigame;

TextAsset::TextAsset(const char* name)
{
    File f(name, E_RESOURCE_FT);
    f.read();
    m_length = StringManager::utf8String(f.getData(), f.getSize(), 0) + 1;
    m_content = uni_new uint16[m_length];
    StringManager::utf8String(f.getData(), f.getSize(), m_content);
    f.close();
    init();
}

void TextAsset::init()
{
    bool isNewLine = true;
    for(int32 i = 0; i < m_length; ++i)
    {
        if(m_content[i] != '\n' && m_content[i] != '\r')
        {
            if(isNewLine)
            {
                m_index.push_back(i);
                isNewLine = false;
            }
        }
        else
        {
            m_content[i] = 0;
            isNewLine = true;
        }
    }
    m_index.pop_back();
}

uint16* TextAsset::getByIndex(int32 index)
{
    return m_content + m_index[index];
}

uint16* TextAsset::getByKey(const char* key)
{
    assert((m_index.size() & 1) == 0 && "key value not match");
    for(int32 i = 0, size = m_index.size(); i < size; i += 2)
    {
        if(StringManager::uniCompare(m_content + m_index[i], key) == 0)
        {
            return m_content + m_index[i + 1];
        }
    }
    return 0;
}

uint16* TextAsset::getByKey(const uint16* key)
{
    assert((m_index.size() & 1) == 0 && "key value not match");
    for(int32 i = 0, size = m_index.size(); i < size; i += 2)
    {
        if(StringManager::uniCompare(m_content + m_index[i], key) == 0)
        {
            return m_content + m_index[i + 1];
        }
    }
    return 0;
}
